package dryworks.jsf.parsers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import dryworks.jsf.examples.generator.SiteGeneratorRunner;

public class FacesConfigParser {
	String jspFileURI;

	public String getJspFileURI() {
		return jspFileURI;
	}

	public void setJspFileURI(String jspFileURI) {
		this.jspFileURI = jspFileURI;
	}

	public Document parserXML(InputStream stream)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		DocumentBuilder db;
		dbf.setValidating(false);
		db = dbf.newDocumentBuilder();
		db.setEntityResolver(new EntityResolver() {

			@Override
			public InputSource resolveEntity(String publicId, String systemId)
					throws SAXException, IOException {
				System.out.println("publicId:" + publicId + " systemId:"
						+ systemId);
				return null;
			}
		});
		Document document = db.parse(stream);
		return document;
	}

	public void visitAllNodes(INodeVisitor nodeVisitor)
			throws ParserConfigurationException, SAXException, IOException {
		Document doc = parserXML(new FileInputStream(getJspFileURI()));
		visit(doc, nodeVisitor);
	}

	public void visitAllNodes(INodeVisitor nodeVisitor, InputStream stream)
			throws ParserConfigurationException, SAXException, IOException {
		Document doc = parserXML(stream);
		visit(doc, nodeVisitor);
	}

	private void visit(Node node, INodeVisitor nodeVisitor) {
		nodeVisitor.visit(node);
		NodeList nl = node.getChildNodes();
		for (int i = 0, cnt = nl.getLength(); i < cnt; i++) {
			visit(nl.item(i), nodeVisitor);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			File projectFolder = new File(SiteGeneratorRunner
					.calculateCurrentWorkspaceDir(), "TestICEFaces");
			File t = new File(
					"TestICEFaces/WebContent/WEB-INF/faces-config.xml");
			if (t.exists()) {
				System.err.println("no file!");
			}

			FacesConfigParser parser = new FacesConfigParser();
			parser.setJspFileURI("WebContent/WEB-INF/faces-config.xml");
			NodesNamesCollector collector = new NodesNamesCollector();
			parser.visitAllNodes(collector);
			System.out.println(collector.getNames());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
